<?php
//-----------------------
// Test
//-------------------------

namespace app\coupon\validate;
use think\{Validate,Db};

class Listen extends Validate{
    // 验证规则
    protected  $coupon = 'coupon';
    protected $rule = [
        ['token',               'require',                                          '-13001'],
        ['id',                  'require',                                          '-10022'],
        ['front_visit',         'checkPower',                                       '-11406'],
        //优惠券名称必填,汉字字母数字,长度不超过8
        ['title',               'require|checkData:title|length:1,80',              '-12001|-12002|-12003'],
        //优惠券类型 1：满减 2：折扣 3：代金 ...
        ['total_issuance',      'require|number|min:1|max:2147483647',              '-12005|-12039|-12039|-12039'],
        ['type',                'require|in:1,2,3',                                 '-12004|-12015'],
        ['reach_amount',        'requireIf:type,1|number|length:1,2147483647',      '-12008|-12040|-12040'],
        ['face_value',          'requireIf:type,1|number|min:1|checkData:face_value','-12006|-12006|-12041'],
        ['discount',            'requireIf:type,2|float|between:1.0,10.0',          '-12007|-12033|-12033'],
        ['apiece_limit',        'require|number',                                   '-12009'],
        ['expire_type',         'require|in:1,2',                                   '-12016|-12017'],
        ['start_time',          'requireIf:expire_type,1',                          '-12010'],
        ['end_time',            'requireIf:expire_type,1|checkData:end_time',       '-12011|'],
        ['expire_day',          'requireIf:expire_type,2|number|max:2147483647',    '-12018|-12019|-12019'],
        ['is_link_product',     'require|in:0,1',                                   '-12012'],
        ['product_list',        'requireIf:is_link_product,1|array|checkData:product_list','-12013|-12043'],
        ['member_type_level',   'require|array|checkData:member_type_level',        '-12014|-12014'],
        ['coupon_id',           'require|checkData:coupon_id,status:1',             '-12023|-12023'],
        ['time_limit',          'length:11',                                        '-12027'],
        ['is_weekends_unuse',   'require|in:0,1',                                   '-12025|-12025'],
        ['is_holidays_unuse',   'require|in:0,1',                                   '-12026|-12026'],
        ['is_base_orgin_buy',   'require|in:0,1',                                   '-12028|-12028'],
        // ['expire_remind',       'checkData:expire_remind',                          '-12030'],
        ['is_able_share_get',   'require|in:0,1',                                   '-12029|-12029'],
        ['action_time',         'requireIf:is_able_share_get,1|number',             '-12044|-12045'],
        ['over_time',           'requireIf:is_able_share_get,1|number|checkData:over_time','-12046|-12047'],
        ['frequency',           'requireIf:is_able_share_get,1|number|checkData:frequency','-12048|-12049'],
        ['status',              'require|in:0,1',                                   '-12035|-12036'],
        ['admin_uid',           'require',                                          '-12038'],
        ['code',                'require',                                          '-12051']
    ];
    protected $scene = [
        'create'        => ['token','id','front_visit','title','total_issuance','type','reach_amount','face_value','discount','apiece_limit','expire_type','start_time','end_time','expire_day','is_link_product','product_list','member_type_level','time_limit','is_weekends_unuse','is_holidays_unuse','is_base_orgin_buy','is_able_share_get','action_time',
        'over_time','frequency','status'],
        'edit'          => ['token','id','title','total_issuance'=>'require|number|min:1|max:2147483647|checkData:total_issuance'],
        'list'          => ['token'],
        'detail'        => ['token','id'=>'require|checkData:coupon_id'],
        'get'           => ['token','coupon_id','front_visit'=>'eq:1'],
        'meetingplace'           => ['token','coupon_id','front_visit'=>'eq:1'],
        'del'           => ['token','id'],
        'product_list'  => ['token'],
        'my'            => ['token','front_visit'=>'eq:1'],
        'status'        => ['token','id','status'],
        'share'         => ['token','coupon_id','add_uid'=>'require'],
        'share_detail'  => ['token','coupon_id'],
        'set_handler'   => ['token'],
        'center'        => ['token','uid'=>'require'],
        'car'           => ['token','uid'=>'require'],
        'use'           => ['token','code'],
    ];

    //前后台访问验证
    protected function checkPower($value,$rule,$data){
        //前端访问
        if($value == 1){
            //检测是否具有发布修改优惠券的权限
            if(1){
                return true;
            }else{
                return false;
            }
        }
        return true;
    }

    /**
     * [checkData description]
     * @param  [type] $value [description]
     * @param  [type] $rule  [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    protected function checkData($value,$rule,$data){
        if(false !== strpos($rule,',')){
            list($field,$condition) = explode(',',$rule,2);
        }else{
            $field = $rule;
        }
        $now_time = \request()->time();
        try{
            $check_rs = false;
            switch ($field) {
                //检查优惠券编号
                case 'coupon_id':
                    $map = [
                        'id'        => $value,
                        'web_id'    => $data['web_id'],
                        'lang_id'   => $data['lang_id']
                    ];
                    if(!empty($condition)){
                        $condition_list = explode(';',$condition);
                        foreach ($condition_list as $key => $value) {
                            list($field_key,$field_value) = explode(':',$value);
                            $map[$field_key] = strpos($field_value,'-')?explode('-',$field_value):$field_value;
                        }
                    }
                    return Db::name('Coupon')->where($map)->count()== 1?:-12023;
                //检查面值是否合理
                case 'face_value':
                    switch($data['type']){
                        case 1:
                            $check_rs = $value<$data['reach_amount'];
                            break;
                        case 3:
                            $check_rs = !empty($data['reach_amount'])?$value<$data['reach_amount']:$value>0;
                            break;
                        default:
                            $check_rs = true;break;
                    }
                    return $check_rs?:-12041;
                //检查过期提醒的天数是否合理
                // case 'expire_remind':
                //     switch ($data['expire_type']) {
                //         case 1:
                //             $check_rs = (($data['end_time']-$data['start_time'])/3600/24) >$value;
                //             break;
                //         case 2:
                //             $check_rs = $data['expire_day'] > $value;
                //             break;
                //         default:
                //             return false;
                //     }
                //     return $check_rs?:-12030;
                //检查过期时间
                case 'end_time' :
                    $check_rs = $value > $data['start_time'] && $value > $now_time;
                    return $check_rs?:-12042;
                //检查活动过期时间
                case 'over_time':
                    $check_rs = $value>$data['action_time'] && $value > $now_time;
                    return $check_rs?:-12047;
                //检查活动可分享次数
                case 'frequency':
                    $check_rs = $data['total_issuance']>=$value;
                    return $check_rs?:-12049;
                //修改发行总量时，不可以少于当前领取的人数
                case 'total_issuance':
                    $check_rs = $data['total_issuance']>=$data['total_get'];
                    return $check_rs?:-12039;
                //检查会员类型
                case 'member_type_level':
                    return true;
                //检查产品列表
                case 'product_list':
                    return true;
                case 'title':
                    $check_rs = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-\.]+$/u');
                    return$check_rs?:-12002;
                default:
                    return -2017;
            }
        }catch(\Exception $e){
            return -2017;
        }
    }
    /**
     * 使用正则验证数据
     * @access protected
     * @param mixed     $value  字段值
     * @param mixed     $rule  验证规则 正则规则或者预定义正则名
     * @return mixed
     */
    protected function regex($value, $rule){
        if (isset($this->regex[$rule])) {
            $rule = $this->regex[$rule];
        }
        if (0 !== strpos($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) {
            // 不是正则表达式则两端补上/
            $rule = '/^' . $rule . '$/';
        }
        return 1 === preg_match($rule, (string) $value);
    }
}